package dailyhealth.controller;

import dailyhealth.controller.vo.DailyHealthVO;
import dailyhealth.service.DailyHealthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import util.ErrorCode;
import util.ResponseUtil;

import java.lang.reflect.Field;

/**
 * @author: cjn
 * @date: 2021/2/8 22:14
 */
@CrossOrigin(origins = {"*"}, maxAge = 3600)
@RestController
@RequestMapping("/api/dailyhealth")
public class DailyHealthController {
    @Autowired
    private DailyHealthService dailyHealthService;

    @RequestMapping(value = "/getScore", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getScoreAndSuggestion(@RequestBody DailyHealthVO dailyHealthVO){
        if(isValidParams(dailyHealthVO)){
            return dailyHealthService.getScoreAndSuggestion(dailyHealthVO);
        }else{
            return ResponseUtil.getResponseString(ErrorCode.NOT_EXIST, "数据格式有误", "数据格式有误，请重新输入!");
        }

    }

    //利用反射机制检查前端数据是否为空
    private static boolean isValidParams(DailyHealthVO dailyHealthVO){
        if (dailyHealthVO == null){
            return false;
        }
        try {
            for (Field field: dailyHealthVO.getClass().getDeclaredFields()){
                field.setAccessible(true); //设置属性可访问
                Object value = field.get(dailyHealthVO); //获取属性值
                //处理String类型属性
                if (field.getType() == String.class){
                    String val = (String)value;
                    if (val == null || "".equals(val.trim())){
                        return false;
                    }
                } else if(field.getType() == Double.class){
                    //处理Double类型属性
                    if(value == null){
                        return false;
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    //测试
    public static void main(String[] args) {
        DailyHealthVO dailyHealthVO = new DailyHealthVO();
        //设置对象初始值
        try{
            for (Field field: dailyHealthVO.getClass().getDeclaredFields()){
                field.setAccessible(true); //设置属性可访问
                if (field.getType() == String.class){
                    field.set(dailyHealthVO, "abc");
                } else if(field.getType() == Double.class){
                    field.set(dailyHealthVO, 0.0);
                }
            }
        } catch (IllegalAccessException e){
            e.printStackTrace();
        }

        //修改初始值
        dailyHealthVO.setAccidents("   ");

        System.out.println(isValidParams(dailyHealthVO));

    }
}
